#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""PDF处理API端点"""

import os
import logging
import tempfile
from typing import List, Dict, Any, Optional

from fastapi import APIRouter, UploadFile, File, HTTPException, BackgroundTasks, Query, Depends
from fastapi.responses import JSONResponse
from pydantic  import BaseModel, Field

from app.core.config import settings
from app.services.pdf_service import PDFService
from app.models.pdf_models import ExtractResponse, TableData, PDFMetadata

# 创建日志记录器
logger = logging.getLogger(__name__)

# 创建路由器
router = APIRouter()

# 获取PDF服务实例
def get_pdf_service():
    return PDFService()

@router.post(
    "/extract",
    response_model=ExtractResponse,
    summary="提取PDF表格数据",
    description="上传PDF文件并提取其中的表格数据"
)
async def extract_pdf_data(
    file: UploadFile = File(...),
    detect_titles: bool = Query(True, description="是否检测表格标题"),
    merge_tables: bool = Query(True, description="是否合并跨页表格"),
    pdf_service: PDFService = Depends(get_pdf_service)
):
    """提取PDF文件中的表格数据"""
    # 检查文件类型
    if not file.filename.lower().endswith(".pdf"):
        raise HTTPException(
            status_code=400,
            detail="只支持PDF文件格式"
        )
    
    # 检查文件大小
    try:
        file_size = 0
        file_content = await file.read()
        file_size = len(file_content)
        
        # 检查文件大小是否超过限制
        max_size = settings.MAX_UPLOAD_SIZE * 1024 * 1024  # 转换为字节
        if file_size > max_size:
            raise HTTPException(
                status_code=400,
                detail=f"文件大小超过限制，最大允许{settings.MAX_UPLOAD_SIZE}MB"
            )
        
        # 创建临时文件
        with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_file:
            temp_file.write(file_content)
            temp_file_path = temp_file.name
        
        try:
            # 提取PDF数据
            logger.info(f"开始处理PDF文件: {file.filename}")
            result = pdf_service.extract_tables_from_pdf(
                temp_file_path,
                detect_titles=detect_titles,
                merge_tables=merge_tables
            )
            
            # 构建响应
            response = ExtractResponse(
                filename=file.filename,
                metadata=result["metadata"],
                tables=result["tables"]
            )
            
            logger.info(f"PDF处理完成: {file.filename}, 提取了{len(result['tables'])}个表格")
            return response
            
        except Exception as e:
            logger.error(f"PDF处理错误: {str(e)}")
            raise HTTPException(
                status_code=500,
                detail=f"PDF处理错误: {str(e)}"
            )
        finally:
            # 删除临时文件
            if os.path.exists(temp_file_path):
                os.unlink(temp_file_path)
    
    except Exception as e:
        logger.error(f"文件上传错误: {str(e)}")
        raise HTTPException(
            status_code=500,
            detail=f"文件上传错误: {str(e)}"
        )

@router.post(
    "/analyze",
    response_model=Dict[str, Any],
    summary="分析PDF文件",
    description="上传PDF文件并进行结构分析，返回文件元数据和结构信息"
)
async def analyze_pdf(
    file: UploadFile = File(...),
    pdf_service: PDFService = Depends(get_pdf_service)
):
    """分析PDF文件结构"""
    # 检查文件类型
    if not file.filename.lower().endswith(".pdf"):
        raise HTTPException(
            status_code=400,
            detail="只支持PDF文件格式"
        )
    
    try:
        file_content = await file.read()
        
        # 创建临时文件
        with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_file:
            temp_file.write(file_content)
            temp_file_path = temp_file.name
        
        try:
            # 分析PDF结构
            logger.info(f"开始分析PDF文件: {file.filename}")
            result = pdf_service.analyze_pdf_structure(temp_file_path)
            
            logger.info(f"PDF分析完成: {file.filename}")
            return result
            
        except Exception as e:
            logger.error(f"PDF分析错误: {str(e)}")
            raise HTTPException(
                status_code=500,
                detail=f"PDF分析错误: {str(e)}"
            )
        finally:
            # 删除临时文件
            if os.path.exists(temp_file_path):
                os.unlink(temp_file_path)
    
    except Exception as e:
        logger.error(f"文件上传错误: {str(e)}")
        raise HTTPException(
            status_code=500,
            detail=f"文件上传错误: {str(e)}"
        )